package com.boot.study.controller;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.SecureUtil;
import com.alibaba.druid.pool.DruidDataSource;
import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.boot.study.config.JdbcUtils;
import com.boot.study.domain.DBDatabase;
import com.boot.study.domain.DbDriftDatabase;
import com.boot.study.domain.TestDemo;
import com.boot.study.mapper.DBDatabaseMapper;
import com.boot.study.mapper.DbDriftDatabaseMapper;
import com.boot.study.mapper.TestDemoMapper;
import org.apache.ibatis.annotations.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description
 * @Author likz
 * @Date 2024/8/6 17:34
 **/
@RestController
@RequestMapping("demo")
public class TestDemoController {

    private static final Logger log = LoggerFactory.getLogger(TestDemoController.class);
    @Resource
    private TestDemoMapper testDemoMapper;
    @Resource
    private DBDatabaseMapper dbDatabaseMapper;

    @Resource
    private DbDriftDatabaseMapper dbDriftDatabaseMapper;

    @Resource
    private DynamicRoutingDataSource dynamicRoutingDataSource;





    @GetMapping("createPro")
    public String createPro(){
        // 获取配置的物理库
        List<DBDatabase> dbDatabases = dbDatabaseMapper.selectList(null);
        // 随机获取一个数据
        DBDatabase dbDatabase = RandomUtil.randomEle(dbDatabases);
        saveDriftDatabase(dbDatabase, IdUtil.objectId());

        return "ok";
    }


    @GetMapping("test")
    public String test(@Param("proId") String proId){
        DynamicDataSourceContextHolder.push(proId);
        List<TestDemo> testDemos = testDemoMapper.selectList(null);
        return testDemos.toString();
    }
    @Value("${dbpath}")
    private String dbpath;

    private void saveDriftDatabase(DBDatabase databaseServiceOne,String projectId){

        boolean connectionOK = JdbcUtils.isConnectionOK(databaseServiceOne.getUrl(), databaseServiceOne.getUsername(), databaseServiceOne.getPassword());
        if (!connectionOK){
            log.info("系统异常");
        }

        String DBName = RandomUtil.randomString(SecureUtil.md5(projectId), 10);

        boolean dbOK = JdbcUtils.isCreateDatabaseOK(databaseServiceOne.getUrl(), databaseServiceOne.getUsername(), databaseServiceOne.getPassword(), DBName);
        if (!dbOK){
            log.info("系统异常");
        }

        String dbUserName = RandomUtil.randomString(10);
        String dbUserPassword = RandomUtil.randomString(12);
        String spUserName = RandomUtil.randomString(11);
        String spPassword = RandomUtil.randomString(13);

        boolean dbDatabaseUserOK = JdbcUtils.isCreateDatabaseUserOK(databaseServiceOne.getUrl(),
                databaseServiceOne.getUsername(),
                databaseServiceOne.getPassword(),
                DBName,
                dbUserName,
                dbUserPassword
        );
        if (!dbDatabaseUserOK){
            log.info("系统异常");
        }

        boolean spDatabaseUserOK = JdbcUtils.isCreateDatabaseUserOK(databaseServiceOne.getUrl(),
                databaseServiceOne.getUsername(),
                databaseServiceOne.getPassword(),
                DBName,
                spUserName,
                spPassword
        );
        if (!spDatabaseUserOK){
            log.info("系统异常");
        }
        String sqlFile = "D:\\data\\sql\\init.sql";
        boolean inited = JdbcUtils.initDB(databaseServiceOne.getUrl()+"/"+DBName, dbUserName, dbUserPassword, sqlFile);
        if (!inited){
            log.info("系统异常");
        }

        DbDriftDatabase dbDriftDatabase = new DbDriftDatabase();
        dbDriftDatabase.setId(IdUtil.objectId());
        dbDriftDatabase.setDbname(DBName);
        dbDriftDatabase.setUrl(databaseServiceOne.getUrl());
        dbDriftDatabase.setDbpassword(dbUserPassword);
        dbDriftDatabase.setDbusername(dbUserName);
        dbDriftDatabase.setSpusername(spUserName);
        dbDriftDatabase.setSppassword(spPassword);
        dbDriftDatabase.setSpmax("2");
        dbDriftDatabase.setProjectId(projectId);
        dbDriftDatabaseMapper.insert(dbDriftDatabase);
        Map<String, String> map = new HashMap<>();
        map.put("username",dbDriftDatabase.getDbusername());
        map.put("password",dbDriftDatabase.getDbpassword());
        map.put("url",dbDriftDatabase.getUrl());
        map.put("dbname",dbDriftDatabase.getDbname());
        map.put("projectId",dbDriftDatabase.getProjectId());
        // 添加到DynamicDatasource
        DruidDataSource dataSource = JdbcUtils.getInitDBConfig();
        dataSource.setUsername(map.get("username"));
        dataSource.setPassword(map.get("password"));
        dataSource.setUrl(map.get("url")+"/"+map.get("dbname")+"?allowMultiQueries=true&useUnicode=true&useSSL=false&allowPublicKeyRetrieval=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&autoReconnect=true&nullCatalogMeansCurrent=true");
        dynamicRoutingDataSource.addDataSource(map.get("projectId"),dataSource);
        log.info("======加载动态数据库完成：ProjectId="+map.get("projectId"));
    }


    public void addDB(String projectId){
//        EdcDbDriftDatabase dbDriftDatabase = edcDbDriftDatabaseMapper.selectOne(projectId);
        DruidDataSource dataSource = JdbcUtils.getInitDBConfig();
//        dataSource.setUsername(dbDriftDatabase.getDbusername());
//        dataSource.setPassword(dbDriftDatabase.getDbpassword());
//        dataSource.setUrl(dbDriftDatabase.getUrl()+"/"+dbDriftDatabase.getDbname()+"?allowMultiQueries=true&useUnicode=true&useSSL=false&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&autoReconnect=true&nullCatalogMeansCurrent=true");
//        dynamicRoutingDataSource.addDataSource(dbDriftDatabase.getProjectId(),dataSource);
//        log.info("======加载动态数据库完成：ProjectId="+dbDriftDatabase.getProjectId());


//        dataSource.setUsername(map.get("username"));
//        dataSource.setPassword(map.get("password"));
//        dataSource.setUrl(map.get("url")+"/"+map.get("dbname")+"?allowMultiQueries=true&useUnicode=true&useSSL=false&allowPublicKeyRetrieval=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&autoReconnect=true&nullCatalogMeansCurrent=true");
//        dynamicRoutingDataSource.addDataSource(map.get("projectId"),dataSource);
//        log.info("======加载动态数据库完成：ProjectId="+map.get("projectId"));

    }




}
